﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Data.ConnectionUI;
using devtm.Configuration;
using System.Configuration;
using System.Windows.Forms;
using devtm.Types.LazyLoading;


namespace devtm.Editor.Configuration.Templates
{

    public static class ConfigurationConnectionStringSettingsActions
    {

        public static bool EditConnectionString(Object sectionElement)
        {


            IElementSection section = (sectionElement as IElementSection);

            ConnectionStringSettings sect =
                (ConnectionStringSettings)section.ConfigurationElement;

            string ConnectionString = sect.ConnectionString;

            DataConnectionDialog dcd = new DataConnectionDialog();
            DataConfiguration dcs = new DataConfiguration(null);

            dcs.LoadConfiguration(dcd, "", "");

            if (!LoadParameter(dcd, dcs, ConnectionString))
                dcs.LoadConfiguration(dcd, "", "");

            //"Integrated Security=True"
            string sauve = dcd.ConnectionString;
            try
            {
                dcd.ConnectionString = ConnectionString;
            }
            catch (Exception)
            {
                dcd.ConnectionString = sauve;
            }

            if (DataConnectionDialog.Show(dcd) == DialogResult.OK)
            {
                sect.ConnectionString = dcd.ConnectionString;

                foreach (IConfigProperty conf in section.Children)
                    conf.RefreshForm();

                return true;

            }

            return false;

        }


        private static bool LoadParameter(DataConnectionDialog dcd, DataConfiguration dcs, String conn)
        {
            foreach (DataSource ds in dcd.DataSources)
                foreach (DataProvider dp in ds.Providers)
                    if (dp.Name == "System.Data.SqlClient")      //conn.ProviderName
                    {
                        dcs.LoadConfiguration(dcd, ds.Name, dp.Name);
                        return true;
                    }
            return false;
        }



    }
}
